//
//  BHApplyUserInfoEditeViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/18.
//  报名信息查看或者修改

import UIKit

class BHApplyUserInfoEditeViewController: BHBaseViewController {
    var refreshDetailInfoBlock:(() -> Void)?
    
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .plain)
        view.register(UINib.init(nibName: "BHUserInfoWriteCell", bundle: nil), forCellReuseIdentifier: "BHUserInfoWriteCell")
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-(BHApplyUserInfoEditeBottomView.height))
        view.delegate = self
        view.dataSource = self
        view.bounces = false
        return view
    }()
    
    lazy var editeBottomView: BHApplyUserInfoEditeBottomView = {
        let view = BHApplyUserInfoEditeBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.height-(BHApplyUserInfoEditeBottomView.height), width: UIScreen.width, height: BHApplyUserInfoEditeBottomView.height)
        view.isHidden = true
        return view
    }()
    
    lazy var serviceManager: BHMeUserFunServiceManager = {
        let manager = BHMeUserFunServiceManager.init()
        return manager
    }()
    
    // 0默认赛事的报名信息修改  1趣玩的报名信息修改  2赛事报名详情的队长添加报名信息
    var editeType: Int = 0
    // 赛事的报名信息
    var model: BHGameApplyUserModel!
    var canEdite: Bool = false // 如果不是队长就不能编辑
    
    fileprivate var allCustomDic: [String:Any] = [:]
    
    // 趣玩的报名信息
    var applyFunDetailModel: BHUserFunApplyDetailModel!
    fileprivate var tempName: String = ""
    fileprivate var tempPhone: String = ""
    
    // 添加报名信息
    var appendUserInfoModel = BHUserGameApplyDetailModel.init()

    fileprivate let nameArray: [String] = ["姓名","身份证号","手机号码"]
    fileprivate let placeArray: [String] = ["请输入姓名","请输入身份证号","请输入手机号码"]
    fileprivate var infoEditing: Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "详情"
        self.bh_navigationBar.rightBtn.isHidden = false
        self.bh_navigationBar.rightBtn.setTitle("修改", for: .normal)
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.editeBottomView)
    
        self.editeBottomView.cancelBtn.addBtnAction(action: {[weak self] (_) in
            self?.infoEditing = false
            self?.tableView.reloadData()
            self?.editeBottomView.isHidden = true
            self?.bh_navigationBar.rightBtn.isHidden = false
        }, for: .touchUpInside)
        
        // 保存修改
        self.editeBottomView.saveBtn.addBtnAction(action: {[weak self] (_) in
            if self?.editeType == 1 {
                if self?.tempName.isEmpty == true {
                    BHToast.toast(text: "请填写报名人姓名")
                    return
                }
                if self?.tempPhone.isEmpty == true {
                    BHToast.toast(text: "请填写报名人手机号码")
                    return
                }
                // 没有修改
                if (self?.tempName == self?.applyFunDetailModel.signUserName) && (self?.tempPhone == self?.applyFunDetailModel.signUserPhone) {
                    self?.navigationController?.popViewController(animated: true)
                }else {
                    self?.serviceManager.editeApplyInfoService(signupId: self?.applyFunDetailModel.signupId ?? "", name: self?.tempName ?? "", phone: self?.tempPhone ?? "")
                }
            }else { // 赛事的修改
                self?.checkEdite()
            }
            
        }, for: .touchUpInside)
        
        if self.editeType == 1 {
            self.serviceManager.funId = self.applyFunDetailModel.funId
            self.tempPhone = self.applyFunDetailModel.signUserPhone
            self.tempName = self.applyFunDetailModel.signUserName
            self.editeApplyInfoResponse()
        }else if self.editeType == 0{ // 赛事报名的修改
            
            self.bh_navigationBar.rightBtn.isHidden = !self.canEdite
            self.allCustomDic = self.model.allCustomDic
            self.tableView.reloadData()
        }else {
            self.bh_navigationBar.title_label.text = "添加"
            self.bh_navigationBar.rightBtn.setTitle("保存", for: .normal)
            self.allCustomDic = self.appendUserInfoModel.enrollJsonDic
            self.tableView.reloadData()
        }
    }

    
    override func rightBtnAction() {
        self.view.endEditing(true)
        if self.editeType == 2 { // 此时为保存
            self.checkEdite()
        }else {
            self.infoEditing = !self.infoEditing
            self.tableView.reloadData()
            self.editeBottomView.isHidden = !self.infoEditing
            self.bh_navigationBar.rightBtn.isHidden = self.infoEditing
        }
    }
}
extension BHApplyUserInfoEditeViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.editeType == 0 {
            return self.model.allCustomDic.count
        }
        if self.editeType == 2 {
            return self.appendUserInfoModel.enrollJsonDic.count
        }
        return self.nameArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.editeType == 1 {
            if indexPath.row == 1 {
                return 0
            }
        }
       return 53
    }
    
}

extension BHApplyUserInfoEditeViewController: UITableViewDelegate {
 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHUserInfoWriteCell", for: indexPath) as! BHUserInfoWriteCell
        if self.editeType == 0 {
            let keyArray = Array(self.model.allCustomDic.keys)
            let valueArray = Array(self.allCustomDic.values)

            let key = keyArray[indexPath.row]
            
            cell.name_label.text = key
            cell.infoTextFiled.text = valueArray[indexPath.row] as? String
            cell.infoTextFiled.placeholder = "请填写\(key)"
            cell.infoTextDidEndEditingBlock = { [weak self] text in
                self?.allCustomDic[key] = text
            }
            cell.infoTextFiled.isEnabled = self.infoEditing

        }else if self.editeType == 1{
            cell.name_label.text = self.nameArray[indexPath.row]
            cell.infoTextFiled.placeholder = self.placeArray[indexPath.row]
            if indexPath.row == 0 {
                if self.editeType == 1 { // 报名修改
                    cell.infoTextFiled.text = self.applyFunDetailModel.signUserName
                }
                cell.infoTextFiled.keyboardType = .default

            }else if indexPath.row == 1 {
                cell.infoTextFiled.keyboardType = .default
            }else {
                if self.editeType == 1 { // 报名修改
                    cell.infoTextFiled.text = self.applyFunDetailModel.signUserPhone
                }
                cell.infoTextFiled.keyboardType = .numberPad
            }
            cell.infoTextDidEndEditingBlock = { [weak self] text in
                if indexPath.row == 0 {
                    self?.tempName = text
                }
                if indexPath.row == 1 {
                    
                }
                if indexPath.row == 2 {
                    self?.tempPhone = text
                }
            }
            cell.infoTextFiled.isEnabled = self.infoEditing
        }else {
            let keyArray = Array(self.appendUserInfoModel.enrollJsonDic.keys)
            let valueArray = Array(self.allCustomDic.values)

            let key = keyArray[indexPath.row]
            
            cell.name_label.text = key
            cell.infoTextFiled.text = valueArray[indexPath.row] as? String
            cell.infoTextFiled.placeholder = "请填写\(key)"
            cell.infoTextDidEndEditingBlock = { [weak self] text in
                self?.allCustomDic[key] = text
            }
            cell.infoTextFiled.isEnabled = true
        }
    
        return cell
    }
}


extension BHApplyUserInfoEditeViewController {
    func editeApplyInfoResponse()  {
        /**
         0 修改信息
         1 退出趣玩
         2 移除报名用户
         3 解散趣玩
         */
        self.serviceManager.responseForCompleteHandlerBlock = {[weak self] (success,errorMsg,type) in
            SVProgressHUD.dismiss()
            if success == false {
                BHToast.toast(text: errorMsg)
                return
            }
            if type == 0 {
                self?.refreshDetailInfoBlock?()
                self?.navigationController?.popViewController(animated: true)
            }
            
        }
    }
}


// MARK: 修改赛事报名信息
extension BHApplyUserInfoEditeViewController {
    func checkEdite()  {
        for (key,value) in self.allCustomDic {
            if value is String {
                let text = value as! String
                if text.isEmpty == true {
                    BHToast.toast(text: "请填写\(key)")
                    return
                }
            }else {
                if value is NSNull {
                    BHToast.toast(text: "请填写\(key)")
                    return
                }
            }
        }
        if self.editeType == 0 {
            self.editeApplyGameService()
        }else {
            self.appendUserInfoService()
        }
    }
    
    func editeApplyGameService()  {
        let dic = self.editeGameInfoDic()
        
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.put(url: String.myGame_editeApplyInfo_url, paramters: dic) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "修改成功")
                self.refreshDetailInfoBlock?()
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    func editeGameInfoDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        if self.editeType == 0 {
            dic["id"] = self.model.applyid
        }else {
            dic["eventSignupId"] = self.appendUserInfoModel.applyId
        }
        let json = NSDictionary(dictionary: self.allCustomDic).toJsonString()
        dic["allCustom"] = json
        return dic
    }
}


// MARK: 赛事-队长添加报名信息
extension BHApplyUserInfoEditeViewController {
    func appendUserInfoService()  {
        let dic = self.editeGameInfoDic()
        
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.post(url: String.myGame_addApplyInfo_url, paramters: dic) {[unowned self] (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "添加成功")
                self.refreshDetailInfoBlock?()
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
